"""
---------------------------------------------------------------------
- File: orm_crud.py
- Date: 2025/9/23
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 数据库ORM增删改查
---------------------------------------------------------------------
"""

from typing import Type, Any
from tortoise import models


class OrmCRUD:
    def __init__(self, model: Type[models.Model]):
        self.model = model

    async def create(self, **kwargs: Any) -> Any:
        """新增"""
        result = await self.model.create(**kwargs)
        return await result

    async def delete(self, id: int | str) -> Any:
        """删除
        :param id: 主键id
        对象不存在返回None
        删除成功返回空对象 {}
        """
        obj = await self.model.get_or_none(id=id)
        if obj is None:
            return None
        await obj.delete()
        return {}

    async def batch_delete(self, ids: list[int | str]) -> Any:
        """批量删除
        :param ids: 主键id列表
        删除成功返回空对象 {}
        """
        await self.model.filter(id__in=ids).delete()
        return {}

    async def update(self, data: Any, id: int | str) -> Any:
        """更新
        :param data: 要更新的数据
        :param id: 主键id
        对象不存在返回None
        更新成功返回更新后的对象
        """
        obj = await self.model.get_or_none(id=id)
        if obj is None:
            return None
        await obj.update_from_dict(data).save()
        return obj

    async def get(self, id: int | str) -> Any:
        """查询
        :param id: 主键id
        对象不存在返回None
        查询成功返回对象
        """
        obj = await self.model.get_or_none(id=id)
        if obj is None:
            return None
        return obj

    async def get_list(self, page: int = 1, page_size: int = 10, **kwargs: Any) -> Any:
        """列表
        :param page_size: 每页数量
        :param page: 当前页
        :param kwargs: 查询条件
        查询成功返回列表
        """
        queryset = self.model.filter(**kwargs)
        queryset = queryset.limit(page_size).offset((page - 1) * page_size)
        return await queryset.all()
